package dao.hibernate;

import java.util.List;

import org.hibernate.Session;

import users.UpdateMessageListener;

import dao.NewspaperDAO;
import model.Newspaper;

/**
 * Implementation of a DAO to allow modifications of a newspaper in a
 * MySQL database using Hibernate.
 */
public class NewspaperDAOHibernateImpl implements NewspaperDAO {

    /**
     * Get all the newspapers in the database.
     *
     * @return  a list with the newspapers in the database
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<Newspaper> getNewspapers() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        List<Newspaper> newspapers = (List<Newspaper>)
                session.createQuery("from Newspaper").list();

        session.getTransaction().commit();

        for (Newspaper np : newspapers) {
            //set name of the topics to communicate with the overlay manager
            np.setOmAssigTopic("brokerAssig." + np.getClientId());
            np.setOmUpdatesTopic("brokerUpdates." + np.getClientId());

            //set listener to update messages from the overlay manager
            np.setOmUpMsgListener(new UpdateMessageListener(np));
        }

        return newspapers;
    }

}
